package com.party.jackclientandroid.ui_home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.party.jackclientandroid.R;
import com.party.jackclientandroid.api.CommentOrReplyService;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.PhotoService;
import com.party.jackclientandroid.BaseActivityTitle;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.CommonResult;
import com.party.jackclientandroid.bean.ImageBean;
import com.party.jackclientandroid.bean.OSSConfig;
import com.party.jackclientandroid.controller.AliyunOSSController;
import com.party.jackclientandroid.utils.MLogUtils;
import com.party.jackclientandroid.view.SimpleRatingBar;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

public class AddCommentActivity extends BaseActivityTitle {
    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;
    @BindView(R.id.taste_ratingbar)
    SimpleRatingBar taste_ratingbar;
    @BindView(R.id.envir_ratingbar)
    SimpleRatingBar envir_ratingbar;
    @BindView(R.id.service_ratingbar)
    SimpleRatingBar service_ratingbar;
    @BindView(R.id.comment_content_et)
    EditText comment_content_et;
    @BindView(R.id.submit_btn)
    Button submit_btn;

    private ArrayList<ImageBean> imageBeanList = new ArrayList<>();
    private List<String> imagePathList = new ArrayList<>();//需要上传到OSS的图片路径List
    private PhotoService photoService;
    private AliyunOSSController ossController;
    private CommonAdapter commonAdapter;
    private static final String TAG = "AddPhotoActivity";
    private int currEditPosition = 0;//表示当前正在编辑哪个图片的名字的位置
    private int currUploadOSSPostion = 0;//表示当前正在上传至OSS的位置
    private int currUploadServerPosition = 0;//表示当前正在上传至服务器的位置
    private CommentOrReplyService commentOrReplyService;
    private long orderId;
    private long shopId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_comment);
        receivePassDataIfNeed(getIntent());
        setTitle("评价");
        initData();
    }

    protected void receivePassDataIfNeed(Intent intent) {
        orderId = intent.getLongExtra("orderId", -1L);
        shopId = intent.getLongExtra("shopId", -1L);
    }

    protected void initData() {

        commentOrReplyService = new CommentOrReplyService(this);
        ossController = new AliyunOSSController(this);
        imageBeanList.add(new ImageBean());

        GridLayoutManager gridLayoutManager = new GridLayoutManager(mActivity, 5);
        commonAdapter = new CommonAdapter<ImageBean>(mActivity, R.layout.item_photo, imageBeanList) {
            @Override
            protected void convert(ViewHolder viewHolder, final ImageBean bean, final int position) {
                if (!TextUtils.isEmpty(bean.getImgPath())) {
                    mApplication.getImageLoaderFactory().loadCommonImgByUrl(mActivity, bean.getImgPath(), (ImageView) viewHolder.getView(R.id.iv_picture));
                } else {
                    mApplication.getImageLoaderFactory().loadCommonImgByUrl(mActivity, R.mipmap.add_photo, (ImageView) viewHolder.getView(R.id.iv_picture));
                }
            }
        };
        recycler_view.setLayoutManager(gridLayoutManager);
        recycler_view.setAdapter(commonAdapter);
        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (TextUtils.isEmpty(imageBeanList.get(position).getImgPath())) {
                    if (choosePictureController != null) {
                        choosePictureController.clearBeforeChoosePictures();
                        choosePictureController.handleToChooseCropPictures();
                    }
                } else {
                    currEditPosition = position;
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    /**
     * 接收选择照片之后的结果,由于使用了裁剪只会返回一张图片数据,需要插入在之前图片集合的后面
     *
     * @param list
     */
    @Override
    public void updateChoosePictures(List<ImageBean> list) {
        imageBeanList.addAll(imageBeanList.size() - 1, list);
        commonAdapter.notifyDataSetChanged();
    }

    @OnClick(R.id.submit_btn)
    public void handleClickSth(View view) {
        if (!TextUtils.isEmpty(comment_content_et.getText().toString())) {
            uploadData();
        }
    }

    /**
     * 上传图片第一步
     */
    private void uploadData() {
        if (imageBeanList.isEmpty()) {
            //showToast("没有图片！");
            submitData("");
        } else {
            showLoadingDialog("上传图片中。。。。");
            for (ImageBean imageBean : imageBeanList) {
                imagePathList.add(imageBean.getImgPath());
            }
            doUploadPictures();
        }
    }

    /**
     * 上传图片第二步
     */
    private void doUploadPictures() {
        // 第一步先服务器获取oss
        addDisposableIoMain(ossController.getOssConfig("1"), new DefaultConsumer<OSSConfig>(mApplication) {
            @Override
            public void operateError(String message) {
                super.operateError(message);
                hideAlertDialog();
                //showToast("上传异常，请稍后上传");
            }

            @Override
            public void operateSuccess(BaseResult<OSSConfig> baseBean) {
                doUploadPictures(baseBean.getData());
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                hideAlertDialog();
                //showToast("上传异常，请稍后上传kkkkkkkkkkk");
            }
        });
    }

    /**
     * 上传图片第三步
     *
     * @param ossConfig
     */
    private void doUploadPictures(OSSConfig ossConfig) {
        ossController.initOssConfig(ossConfig, mActivity);
        // 这里需要传入店铺的id
        addDisposableIoMain(ossController.uploadPicturesSync(shopId + "", imagePathList, false), new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                MLogUtils.d("doUploadPictures", "上传之后的图片地址集合为===" + s);
                submitData(s);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                hideAlertDialog();
                //showToast("上传图片失败===" + throwable.getMessage());
            }
        });
    }

    private void submitData(String imagePathArr) {
        Map<String, String> tokenMap = getTokenMap();
        tokenMap.put("shopId", shopId + "");
        tokenMap.put("content", comment_content_et.getText().toString());
        tokenMap.put("tasteScore", ((int) (taste_ratingbar.getRating() * 2)) + "");
        tokenMap.put("enviroScore", ((int) (envir_ratingbar.getRating() * 2)) + "");
        tokenMap.put("serviceScore", ((int) (service_ratingbar.getRating() * 2)) + "");
        tokenMap.put("commentImg", imagePathArr);
        tokenMap.put("orderId", orderId + "");
        tokenMap.put("parentId", "0");
        Log.d(TAG, tokenMap.toString());
        addDisposableIoMain(commentOrReplyService.addComment(tokenMap), new DefaultConsumer<CommonResult>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<CommonResult> result) {
                //showToast("评论成功");
                hideAlertDialog();
                showToast("评论成功");
                finish();
            }
        });
    }
}
